package com.ding.second.action;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ding.second.common.UUIDUtil;
import com.ding.second.po.Product;
import com.ding.second.po.ProductImage;
import com.ding.second.service.ProductImageService;
import com.ding.second.service.ProductServer;

@Controller
@RequestMapping("/edit")
public class EditAction {

	@Autowired
	private ProductServer productServer;
	@Autowired
	private ProductImageService productImageServer;

	@RequestMapping("/addCommodity")
	public String addCommdity(Model model, Product product, @RequestParam("files") CommonsMultipartFile[] files,
			HttpServletRequest request) throws Exception {
		String uuidProductId = UUIDUtil.getUUID();
		product.setProductId(uuidProductId);
		product.setProductState(101);
		
		/*得到绝对路径*/
		String realPath = request.getServletContext().getRealPath("/productImages");
		ProductImage productImage = new ProductImage();

		/*保存商品*/
		boolean saveProduct = productServer.insertProduct(product);
		if (saveProduct) {
			/*保存图片*/
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getOriginalFilename();
				String currentName = UUIDUtil.getUUID() + fileName.substring(fileName.lastIndexOf("."), fileName.length());

				productImage.setImageId(UUIDUtil.getUUID());
				productImage.setImageName(currentName);
				productImage.setProductId(uuidProductId);
				productImage.setImageSize(files[i].getSize() + "");
				boolean saveImage = productImageServer.insertImage(productImage);
				if (saveImage) {
					files[i].transferTo(new File(realPath + "/" + currentName));
				}
			}
		}
		
		

		return "redirect:/inquiry/all.do";
	}

}
